/* 
 * Copyright (C) 2012 UTSChedule
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package utsc.apps.utschedule.ui.activities;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;

import utsc.apps.utschedule.R;
import utsc.apps.utschedule.util.AppUtils;
import utsc.apps.utschedule.util.database.DatabaseHelper;
import com.actionbarsherlock.app.SherlockPreferenceActivity;
import com.actionbarsherlock.view.MenuItem;

import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.widget.Toast;

/**
 * This activity is used for maintaining the backward comparability of
 * {@link SherlockPreferenceActivity PreferenceActivity} prior to api 11.
 * 
 */
public class SettingActivity extends SherlockPreferenceActivity implements
		OnPreferenceClickListener, OnClickListener {
	private File[] _backups;
	private AlertDialog _restoreDialog;

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getListView().setCacheColorHint(Color.TRANSPARENT);
		
		//prior to api 11
		//the following method calls are valid
		addPreferencesFromResource(R.xml.preferences);
		findPreference("search_setting").setOnPreferenceClickListener(this);
		findPreference("backup").setOnPreferenceClickListener(this);
		findPreference("restore").setOnPreferenceClickListener(this);
		findPreference("clear_backup").setOnPreferenceClickListener(this);
		findPreference("user_login").setOnPreferenceClickListener(this);
		findPreference("clear_login").setOnPreferenceClickListener(this);
		findPreference("archive").setOnPreferenceClickListener(this);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			return true;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onPreferenceClick(Preference preference) {
		String key = preference.getKey();
		//click handler for each preference
		if (key.equals("search_setting")) {
			// turn the global search on by opening the system search setting
			// page 
			Intent searchSettingIntent = new Intent(SearchManager.INTENT_ACTION_SEARCH_SETTINGS);
			startActivity(searchSettingIntent);
		} else if (key.equals("backup")) {
			//database backup  
			DatabaseHelper.backupDb(this);
		} else if (key.equals("restore")) {
			//restore the database
			_backups = getBackups();
			if (_backups != null && _backups.length > 0) {
				int fileSize = _backups.length;
				String[] fileNames = new String[fileSize];
				for (int i = 0; i < fileSize; i++) {
					fileNames[i] = _backups[i].getName();
				}
				_restoreDialog = new AlertDialog.Builder(this).setTitle("Select a backup").setItems(fileNames, this).create();
				_restoreDialog.show();
			}
		}else if (key.equals("user_login")) {
			//user login setting
			Intent setLoginIntent=new Intent(this, LoginActivity.class);
			setLoginIntent.putExtra("setLogin", true);
			startActivity(setLoginIntent);
		}else if (key.equals("clear_login")) {
			//clear login
			AppUtils.deleteLoginPreferences(this);
			Toast.makeText(this, "Login setting is cleared.", Toast.LENGTH_LONG).show();
		}else if (key.equals("clear_backup")) {
			//clear all the backups
			try {
				clearBackups();
				Toast.makeText(this, "All backups have been cleared!",Toast.LENGTH_LONG).show();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else if (key.equals("archive")) {
			//go to the archive
			Intent timetableArchiveIntent=new Intent(this, TimetableArchiveActivity.class);
			startActivity(timetableArchiveIntent);
		}
		return true;
	}

	@Override
	public void onStop() {
		if (_restoreDialog != null) {
			if (_restoreDialog.isShowing()) {
				_restoreDialog.dismiss();
			}
		}
		super.onStop();
	}

	/**
	 * Retrieves all the database backups from the sd card.
	 * @return
	 */
	private File[] getBackups() {
		File backup = new File(Environment.getExternalStorageDirectory(),
				"/UTSChedule");
		if (backup.isDirectory()) {
			return backup.listFiles(new FilenameFilter() {
				@Override
				public boolean accept(File dir, String filename) {
					if (filename.contains("UTSChedule_")) {
						return true;
					}
					return false;
				}
			});
		}
		return null;
	}

	/**
	 * Clears off all the backup files
	 * @throws IOException
	 */
	private void clearBackups() throws IOException {
		File backup = new File(Environment.getExternalStorageDirectory(),
				"/UTSChedule");
		if (backup.isDirectory()) {
			File[] backups = backup.listFiles(new FilenameFilter() {

				@Override
				public boolean accept(File dir, String filename) {
					if (filename.contains("UTSChedule_")) {
						return true;
					}
					return false;
				}
			});

			if (backups != null) {
				for (File file : backups) {
					if (!file.delete())
						throw new IOException("Failed to delete File.");
				}
			}
		}
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		//the click action handler to handle the selected backup selection
		File selectedBackup = _backups[which];
		DatabaseHelper.restoreDb(selectedBackup.getPath(), this);
	}
}
